from flask import g, Blueprint, request, jsonify, session, redirect
from models import QuestionBank, SingleChoiceQuestionBank, JudgmentalQuestionBank, ShortAnswerQuestionBank, \
    PictureQuestionBank, TeacherQuestionBankRel, MultipleChoiceQuestionsBank
from exts import db, get_time
import os
import time
import pandas as pd
from flask_login import login_required

bp = Blueprint("question_bank", __name__, url_prefix="/question_bank")


# todo before_request
@bp.before_request
@login_required
def before_request():
    pass


# todo add_question_bank
@bp.route("/add_question_bank", methods=["POST"])
def add_question_bank():
    name = request.values.get("name")
    qb = QuestionBank(
        name=name,
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0
    )
    db.session.add(qb)
    db.session.commit()

    return redirect("/admin/question_bank_list_url")


# todo query_all_question_bank
@bp.route("/query_all_question_bank", methods=["GET"])
def query_all_question_bank():
    page = request.values.get("page")
    limit = request.values.get("limit")

    paginate = db.session.query(QuestionBank).paginate(page=int(page), per_page=int(limit))

    return_data = []
    for i in paginate.items:
        return_data.append({
            "id": i.id,
            "name": i.name,
            "create_time": i.create_time,
            "update_time": i.update_time,
            "is_delete": i.is_delete
        })

    data = {
        "code": 0,
        "msg": "",
        "count": len(db.session.query(QuestionBank).all()),
        "data": return_data
    }

    return jsonify(data)


# todo delete_question_bank
@bp.route("/delete_question_bank", methods=["POST"])
def delete_question_bank():
    id_question_bank = request.values.get("id_question_bank")
    try:
        db.session.query(QuestionBank).filter(QuestionBank.id == id_question_bank).delete()
    except:
        return "error"

    db.session.commit()

    return "success"


# todo add_single_choice_question_bank 单选题
@bp.route("/add_single_choice_question_bank", methods=["POST"])
def add_single_choice_question_bank():
    question = request.values.get("question")
    a = request.values.get("a")
    b = request.values.get("b")
    c = request.values.get("c")
    d = request.values.get("d")
    answer = request.values.get("answer")
    id_question_bank = request.values.get("id_question_bank")

    question_bank = db.session.query(QuestionBank).get(id_question_bank)

    s = SingleChoiceQuestionBank(
        question=question,
        a=a,
        b=b,
        c=c,
        d=d,
        answer=answer,
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0,
        question_bank=question_bank
    )
    db.session.add(s)
    db.session.commit()

    return "success"


# todo delete_single_choice_question_bank
@bp.route("/delete_single_choice_question_bank", methods=["POST"])
def delete_single_choice_question_bank():
    id_single_choice_question_bank = eval(request.values.get("id_single_choice_question_bank"))
    for i in id_single_choice_question_bank:
        db.session.query(SingleChoiceQuestionBank).filter(
            SingleChoiceQuestionBank.id == i["id"]).delete()

    db.session.commit()

    return "success"


# todo query_single_choice_question_bank
@bp.route("/query_single_choice_question_bank", methods=["GET"])
def query_single_choice_question_bank():
    page = request.values.get("page")
    limit = request.values.get("limit")
    id_question_bank = request.values.get("id_question_bank")
    question_bank = db.session.query(QuestionBank).get(id_question_bank)
    paginate = db.session.query(SingleChoiceQuestionBank).filter(
        SingleChoiceQuestionBank.id_question_bank == id_question_bank).paginate(page=int(page), per_page=int(limit))
    return_data = []
    for i in paginate.items:
        return_data.append({
            "id": i.id,
            "question": i.question,
            "a": i.a,
            "b": i.b,
            "c": i.c,
            "d": i.d,
            "answer": i.answer,
            "create_time": i.create_time,
            "update_time": i.update_time,
            "is_delete": i.is_delete
        })

    data = {
        "code": 0,
        "msg": "",
        "count": len(question_bank.single_choice_question_bank),
        "data": return_data
    }
    return jsonify(data)


# todo add_multiple_choice_question_bank 多选题
@bp.route("/add_multiple_choice_question_bank", methods=["POST"])
def add_multiple_choice_question_bank():
    question = request.values.get("question")
    a = request.values.get("a")
    b = request.values.get("b")
    c = request.values.get("c")
    d = request.values.get("d")
    checkbox_a = request.values.get("checkbox_a")
    checkbox_b = request.values.get("checkbox_b")
    checkbox_c = request.values.get("checkbox_c")
    checkbox_d = request.values.get("checkbox_d")

    # print(question, a, b, c, d, checkbox_a, checkbox_b, checkbox_c, checkbox_d)
    # return "test"
    # answer = request.values.get("answer")
    answer = ""
    if checkbox_a is not None:
        answer += checkbox_a+"&"
    if checkbox_b is not None:
        answer += checkbox_b+"&"
    if checkbox_c is not None:
        answer += checkbox_c+"&"
    if checkbox_d is not None:
        answer += checkbox_d+"&"
    answer = answer[:-1]
    if answer == "":
        return "多选题答案不能为空"

    id_question_bank = request.values.get("id_question_bank")

    question_bank = db.session.query(QuestionBank).get(id_question_bank)

    m = MultipleChoiceQuestionsBank(
        question=question,
        a=a,
        b=b,
        c=c,
        d=d,
        answer=answer,
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0,
        question_bank=question_bank
    )
    db.session.add(m)
    db.session.commit()

    return redirect("/admin/add_questions_url?id_question_bank="+id_question_bank)


# todo delete_multiple_choice_question_bank
@bp.route("/delete_multiple_choice_question_bank", methods=["POST"])
def delete_multiple_choice_question_bank():
    id_multiple_choice_question_bank = eval(request.values.get("id_multiple_choice_question_bank"))
    for i in id_multiple_choice_question_bank:
        db.session.query(MultipleChoiceQuestionsBank).filter(
            MultipleChoiceQuestionsBank.id == i["id"]).delete()

    db.session.commit()

    return "success"


# todo query_multiple_choice_question_bank
@bp.route("/query_multiple_choice_question_bank", methods=["GET"])
def query_multiple_choice_question_bank():
    page = request.values.get("page")
    limit = request.values.get("limit")
    id_question_bank = request.values.get("id_question_bank")
    question_bank = db.session.query(QuestionBank).get(id_question_bank)
    paginate = db.session.query(MultipleChoiceQuestionsBank).filter(
        MultipleChoiceQuestionsBank.id_question_bank == id_question_bank).paginate(page=int(page), per_page=int(limit))
    return_data = []
    for i in paginate.items:
        return_data.append({
            "id": i.id,
            "question": i.question,
            "a": i.a,
            "b": i.b,
            "c": i.c,
            "d": i.d,
            "answer": i.answer,
            "create_time": i.create_time,
            "update_time": i.update_time,
            "is_delete": i.is_delete
        })

    data = {
        "code": 0,
        "msg": "",
        "count": len(question_bank.multiple_choice_questions_bank),
        "data": return_data
    }
    return jsonify(data)


# todo add_judgmental_question_bank 判断题
@bp.route("/add_judgmental_question_bank", methods=["POST"])
def add_judgmental_question_bank():
    question = request.values.get("question")
    answer = request.values.get("answer")
    id_question_bank = request.values.get("id_question_bank")

    question_bank = db.session.query(QuestionBank).get(id_question_bank)

    j = JudgmentalQuestionBank(
        question=question,
        answer=answer,
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0,
        question_bank=question_bank
    )
    db.session.add(j)
    db.session.commit()

    return "success"


# todo delete_judgmental_question_bank
@bp.route("/delete_judgmental_question_bank", methods=["POST"])
def delete_judgmental_question_bank():
    id_judgmental_question_bank = eval(request.values.get("id_judgmental_question_bank"))
    for i in id_judgmental_question_bank:
        db.session.query(JudgmentalQuestionBank).filter(
            JudgmentalQuestionBank.id == i["id"]).delete()

    db.session.commit()

    return "success"


# todo query_judgmental_question_bank
@bp.route("/query_judgmental_question_bank", methods=["GET"])
def query_judgmental_question_bank():
    page = request.values.get("page")
    limit = request.values.get("limit")
    id_question_bank = request.values.get("id_question_bank")
    question_bank = db.session.query(QuestionBank).get(id_question_bank)
    paginate = db.session.query(JudgmentalQuestionBank).filter(
        JudgmentalQuestionBank.id_question_bank == id_question_bank).paginate(page=int(page), per_page=int(limit))
    return_data = []
    for i in paginate.items:
        return_data.append({
            "id": i.id,
            "question": i.question,
            "answer": i.answer,
            "create_time": i.create_time,
            "update_time": i.update_time,
            "is_delete": i.is_delete
        })

    data = {
        "code": 0,
        "msg": "",
        "count": len(question_bank.judgmental_question_bank),
        "data": return_data
    }

    return jsonify(data)


# todo query_multiple_choice_questions_bank
@bp.route("/query_multiple_choice_questions_bank", methods=["GET"])
def query_multiple_choice_questions_bank():
    page = request.values.get("page")
    limit = request.values.get("limit")
    id_question_bank = request.values.get("id_question_bank")
    question_bank = db.session.query(QuestionBank).get(id_question_bank)
    paginate = db.session.query(MultipleChoiceQuestionsBank).filter(
        MultipleChoiceQuestionsBank.id_question_bank == id_question_bank).paginate(page=int(page), per_page=int(limit))
    return_data = []
    for i in paginate.items:
        return_data.append({
            "id": i.id,
            "question": i.question,
            "a": i.a,
            "b": i.b,
            "c": i.c,
            "d": i.d,
            "answer": i.answer,
            "create_time": i.create_time,
            "update_time": i.update_time,
            "is_delete": i.is_delete
        })

    data = {
        "code": 0,
        "msg": "",
        "count": len(db.session.query(MultipleChoiceQuestionsBank).filter(MultipleChoiceQuestionsBank.id_question_bank == question_bank.id).all()),
        "data": return_data
    }

    return jsonify(data)


# todo add_short_answer_question_bank 简答题
@bp.route("/add_short_answer_question_bank", methods=["POST"])
def add_short_answer_question_bank():
    question = request.values.get("question")
    answer = request.values.get("answer")
    id_question_bank = request.values.get("id_question_bank")

    question_bank = db.session.query(QuestionBank).get(id_question_bank)

    s = ShortAnswerQuestionBank(
        question=question,
        answer=answer,
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0,
        question_bank=question_bank
    )
    db.session.add(s)
    db.session.commit()

    return "success"


# todo delete_short_answer_question_bank
@bp.route("/delete_short_answer_question_bank", methods=["POST"])
def delete_short_answer_question_bank():
    id_short_answer_question_bank = eval(request.values.get("id_short_answer_question_bank"))
    for i in id_short_answer_question_bank:
        db.session.query(ShortAnswerQuestionBank).filter(
            ShortAnswerQuestionBank.id == i["id"]).delete()

    db.session.commit()

    return "success"


# todo query_short_answer_question_bank
@bp.route("/query_short_answer_question_bank", methods=["GET"])
def query_short_answer_question_bank():
    page = request.values.get("page")
    limit = request.values.get("limit")
    id_question_bank = request.values.get("id_question_bank")
    question_bank = db.session.query(QuestionBank).get(id_question_bank)
    paginate = db.session.query(ShortAnswerQuestionBank).filter(
        ShortAnswerQuestionBank.id_question_bank == id_question_bank).paginate(page=int(page), per_page=int(limit))
    return_data = []
    for i in paginate.items:
        return_data.append({
            "id": i.id,
            "question": i.question,
            "answer": i.answer,
            "create_time": i.create_time,
            "update_time": i.update_time,
            "is_delete": i.is_delete
        })
    data = {
        "code": 0,
        "msg": "",
        "count": len(question_bank.short_answer_question_bank),
        "data": return_data
    }
    return jsonify(data)


# todo add_picture_question_bank 带有图片的问题
@bp.route("/add_picture_question_bank", methods=["POST"])
def add_picture_question_bank():
    answer = request.values.get("answer")
    id_question_bank = request.values.get("id_question_bank")

    uploaded_file = request.files.get('question')
    # print(answer,id_question_bank,uploaded_file,sep="\n")

    suffix = '.' + uploaded_file.filename.split('.')[-1]  # 获取文件后缀名
    filename = uploaded_file.filename.replace(suffix, "").replace("\\", "").replace("/", "")
    basedir = os.path.abspath(os.path.dirname(__file__)).replace("blueprints", "")  # 获取当前文件路径
    new_dir = os.path.join("static", "upload", "picture_question_bank",
                           filename + str(int(time.time())) + suffix)  # 拼接相对路径
    uploaded_file_path = os.path.join(basedir, new_dir)  # 拼接图片完整保存路径,时间戳命名文件防止重复
    uploaded_file.save(uploaded_file_path)  # 保存文件
    # size = os.path.getsize(uploaded_file_path)

    question_bank = db.session.query(QuestionBank).get(id_question_bank)

    p = PictureQuestionBank(
        question="/" + new_dir.replace("\\", "/"),
        answer=answer,
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0,
        question_bank=question_bank
    )
    db.session.add(p)
    db.session.commit()

    return redirect("/admin/add_questions_url?id_question_bank=" + id_question_bank)


# todo batch_add_picture_question_bank 批量添加带有图片的问题，文件名为题目答案
@bp.route("/batch_add_picture_question_bank", methods=["POST"])
def batch_add_picture_question_bank():
    id_question_bank = request.values.get("id_question_bank")
    uploaded_file = request.files.get('file')
    # print(id_question_bank, uploaded_file, sep="\n")

    suffix = '.' + uploaded_file.filename.split('.')[-1]  # 获取文件后缀名
    filename = uploaded_file.filename.replace(suffix, "").replace("\\", "").replace("/", "")
    try:
        if len(filename.split("-")) == 3:
            type = filename.split("-")[1]
            answer = filename.split("-")[2]
            if int(type) == 0:
                answer = answer.lower()
            if int(type) == 1:
                answer = int(answer)
                assert answer == 0 or answer == 1
        elif len(filename.split("-")) == 2:
            answer = filename.split("-")[1].lower()
        else:
            int("a")  # 故意抛出异常
    except:
        return "error"
    basedir = os.path.abspath(os.path.dirname(__file__)).replace("blueprints", "")  # 获取当前文件路径
    new_dir = os.path.join("static", "upload", "picture_question_bank",
                           filename + str(int(time.time())) + suffix)  # 拼接相对路径
    uploaded_file_path = os.path.join(basedir, new_dir)  # 拼接图片完整保存路径,时间戳命名文件防止重复
    uploaded_file.save(uploaded_file_path)  # 保存文件
    # size = os.path.getsize(uploaded_file_path)

    question_bank = db.session.query(QuestionBank).get(id_question_bank)

    p = PictureQuestionBank(
        question="/" + new_dir.replace("\\", "/"),
        answer=answer,
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0,
        question_bank=question_bank
    )
    db.session.add(p)
    db.session.commit()

    return redirect("/admin/add_questions_url?id_question_bank=" + id_question_bank)


# todo delete_picture_question_bank
@bp.route("/delete_picture_question_bank", methods=["POST"])
def delete_picture_question_bank():
    id_picture_question_bank = eval(request.values.get("id_picture_question_bank"))
    for i in id_picture_question_bank:
        db.session.query(PictureQuestionBank).filter(PictureQuestionBank.id == i["id"]).delete()

    db.session.commit()

    return "success"


# todo query_picture_question_bank
@bp.route("/query_picture_question_bank", methods=["GET"])
def query_picture_question_bank():
    page = request.values.get("page")
    limit = request.values.get("limit")
    id_question_bank = request.values.get("id_question_bank")
    question_bank = db.session.query(QuestionBank).get(id_question_bank)
    paginate = db.session.query(PictureQuestionBank).filter(
        PictureQuestionBank.id_question_bank == id_question_bank).paginate(page=int(page), per_page=int(limit))
    return_data = []
    for i in paginate.items:
        return_data.append({
            "id": i.id,
            "question": i.question,
            "answer": i.answer,
            "create_time": i.create_time,
            "update_time": i.update_time,
            "is_delete": i.is_delete
        })
    data = {
        "code": 0,
        "msg": "",
        "count": len(question_bank.picture_question_bank),
        "data": return_data
    }
    return jsonify(data)


# todo query_teacher_question_bank_rel
@bp.route("/query_teacher_question_bank_rel", methods=["GET"])
def query_teacher_question_bank_rel():
    return_data = []
    for i in db.session.query(QuestionBank).all():
        return_data.append({
            "id": i.id,
            "name": i.name,
            "teacher": len(
                db.session.query(TeacherQuestionBankRel).filter(TeacherQuestionBankRel.id_question_bank == i.id).all()),
            "create_time": i.create_time,
            "update_time": i.update_time,
            "is_delete": i.is_delete
        })

    data = {
        "code": 0,
        "msg": "",
        "count": len(db.session.query(QuestionBank).all()),
        "data": return_data
    }
    return jsonify(data)


# todo query_banks_belong_to_this_teacher
@bp.route("/query_banks_belong_to_this_teacher", methods=["GET"])
def query_banks_belong_to_this_teacher():
    return_data = []
    for i in g.user.teacher.teacher_question_bank_rel:
        return_data.append({
            "id": i.question_bank.id,
            "name": i.question_bank.name,
            "create_time": i.question_bank.create_time,
            "update_time": i.question_bank.update_time,
            "is_delete": i.question_bank.is_delete
        })

    data = {
        "code": 0,
        "msg": "",
        "count": len(return_data),
        "data": return_data
    }
    return jsonify(data)


# todo add_single_choice_question_from_table
@bp.route("/add_single_choice_question_from_table", methods=["POST"])
def add_single_choice_question_from_table():
    id_question_bank = request.values.get("id_question_bank")
    uploaded_file = request.files.get('file')
    # print(uploaded_file)

    suffix = '.' + uploaded_file.filename.split('.')[-1]  # 获取文件后缀名
    filename = uploaded_file.filename.replace(suffix, "").replace("\\", "").replace("/", "")
    basedir = os.path.abspath(os.path.dirname(__file__)).replace("blueprints", "")  # 获取当前文件路径
    new_dir = os.path.join("static", "upload", "question_table", filename + str(int(time.time())) + suffix)  # 拼接相对路径
    uploaded_file_path = os.path.join(basedir, new_dir)  # 拼接图片完整保存路径,时间戳命名文件防止重复
    uploaded_file.save(uploaded_file_path)  # 保存文件
    size = os.path.getsize(uploaded_file_path)
    df1 = pd.read_excel(uploaded_file_path)  # 读取xlsx中的第一个sheet
    # print(df1)
    # print(df1.values)
    # 4.将xlsx数据转换为字典
    data = []
    for i in df1.index.values:  # 获取行号的索引，并对其遍历
        # 根据i来获取每一行指定的数据，并用to_dict转成字典
        row_data = df1.loc[i, ['question', 'a', 'b', 'c', 'd', 'answer', ]].to_dict()
        data.append(row_data)
    # print(data)
    # return "test"
    for i in data:
        scq = SingleChoiceQuestionBank(
            question=i["question"],
            a=i["a"],
            b=i["b"],
            c=i["c"],
            d=i["d"],
            answer=i["answer"],
            question_bank=db.session.query(QuestionBank).get(id_question_bank),
            create_time=get_time(),
            update_time=get_time(),
            is_delete=0
        )
        db.session.add(scq)

    db.session.commit()

    return redirect("/admin/add_questions_from_table_url?id_question_bank=" + id_question_bank)


# todo add_judgmental_question_from_table
@bp.route("/add_judgmental_question_from_table", methods=["POST"])
def add_judgmental_question_from_table():
    id_question_bank = request.values.get("id_question_bank")
    uploaded_file = request.files.get('file')
    # print(uploaded_file)

    suffix = '.' + uploaded_file.filename.split('.')[-1]  # 获取文件后缀名
    filename = uploaded_file.filename.replace(suffix, "").replace("\\", "").replace("/", "")
    basedir = os.path.abspath(os.path.dirname(__file__)).replace("blueprints", "")  # 获取当前文件路径
    new_dir = os.path.join("static", "upload", "question_table", filename + str(int(time.time())) + suffix)  # 拼接相对路径
    uploaded_file_path = os.path.join(basedir, new_dir)  # 拼接图片完整保存路径,时间戳命名文件防止重复
    uploaded_file.save(uploaded_file_path)  # 保存文件
    size = os.path.getsize(uploaded_file_path)
    df1 = pd.read_excel(uploaded_file_path)  # 读取xlsx中的第一个sheet
    # print(df1)
    # print(df1.values)
    # 4.将xlsx数据转换为字典
    data = []
    for i in df1.index.values:  # 获取行号的索引，并对其遍历
        # 根据i来获取每一行指定的数据，并用to_dict转成字典
        row_data = df1.loc[i, ['question', 'answer', ]].to_dict()
        data.append(row_data)
    # print(data)
    for i in data:
        jq = JudgmentalQuestionBank(
            question=i["question"],
            answer=i["answer"],
            question_bank=db.session.query(QuestionBank).get(id_question_bank),
            create_time=get_time(),
            update_time=get_time(),
            is_delete=0
        )
        db.session.add(jq)

    db.session.commit()

    return redirect("/admin/add_questions_from_table_url?id_question_bank=" + id_question_bank)


# todo add_short_answer_question_from_table
@bp.route("/add_short_answer_question_from_table", methods=["POST"])
def add_short_answer_question_from_table():
    id_question_bank = request.values.get("id_question_bank")
    uploaded_file = request.files.get('file')
    # print(uploaded_file)

    suffix = '.' + uploaded_file.filename.split('.')[-1]  # 获取文件后缀名
    filename = uploaded_file.filename.replace(suffix, "").replace("\\", "").replace("/", "")
    basedir = os.path.abspath(os.path.dirname(__file__)).replace("blueprints", "")  # 获取当前文件路径
    new_dir = os.path.join("static", "upload", "question_table", filename + str(int(time.time())) + suffix)  # 拼接相对路径
    uploaded_file_path = os.path.join(basedir, new_dir)  # 拼接图片完整保存路径,时间戳命名文件防止重复
    uploaded_file.save(uploaded_file_path)  # 保存文件
    size = os.path.getsize(uploaded_file_path)
    df1 = pd.read_excel(uploaded_file_path)  # 读取xlsx中的第一个sheet
    # print(df1)
    # print(df1.values)
    # 4.将xlsx数据转换为字典
    data = []
    for i in df1.index.values:  # 获取行号的索引，并对其遍历
        # 根据i来获取每一行指定的数据，并用to_dict转成字典
        row_data = df1.loc[i, ['question', 'answer', ]].to_dict()
        data.append(row_data)
    # print(data)
    for i in data:
        saq = ShortAnswerQuestionBank(
            question=i["question"],
            answer=i["answer"],
            question_bank=db.session.query(QuestionBank).get(id_question_bank),
            create_time=get_time(),
            update_time=get_time(),
            is_delete=0
        )
        db.session.add(saq)

    db.session.commit()

    return redirect("/admin/add_questions_from_table_url?id_question_bank=" + id_question_bank)
